<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\model\Sms;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\User;
use Illuminate\Support\Facades\Cache;

class LoginController extends BaseController
{
    /**
     * 登录信息接口
     * by 吉星
     */
    // 企业登录获取验证码
    public function code(Request $request){
        $arr = [];
        if(empty($request['phone'])){
            $arr['code'] = '1004';
            $arr['message'] = "手机号不能为空";
        }else{
            $phone = $request['phone'];
            $company_data = Db::table('social_user')
                ->where('phone',$phone)->first();
            $company_data =  json_decode(json_encode($company_data),true);
            $comid = $company_data['company_id'];
            $com = Db::table('social_company')->where('id',$comid)->first();
            $com =  json_decode(json_encode($com),true);
            // echo "<pre>";
            // print_r($company_data);die();
            if($company_data['type'] != 3 && $company_data['company_id'] != ''){
                $arr['code'] = 1003;
                $arr['message'] = '该账户不是企业管理员，请使用会员登录！';
            }else{
                $num = rand(1111,9999);
                $msg = "验证码:".$num."，有效期3分钟【时代出行】";
                $code = new Sms();
                $re = $code -> sendSMS($phone,$msg);
                $data = json_decode($re,true);
                //  dump($data);

                if(empty($com)){
                    $arr['comid'] = 1501;  //企业不存在
                }else{
                    $arr['comid'] = 1500;  //企业存在
                }
                if($data['error'] == 0){
                    $arr['code'] = 1000;
                    $arr['m_code'] = $num;
                    $arr['message'] = '请求成功';
                }else{
                    $arr['code'] = 1002;
                    $arr['m_code'] = $num;
                    if($data['msg'] == 'FREQUENCE_ERROR'){
                        $arr['message'] = '请勿点击太快!';
                    }

                }
            }
        }
        return $arr;
    }
    public function code1(Request $request)
    {
        $arr = [];
        if(empty($request['phone'])){
            $arr['code'] = 1004;
            $arr['message'] = "手机号不能为空";
        }else{
            $phone = $request['phone'];
            // dump($com);
            // dump($company_data);exit;
            $num = rand(1111,9999);
            $msg = "验证码:".$num."，有效期3分钟【时代出行】";
            $code = new Sms();
            $re = $code -> sendSMS($phone,$msg);
            $data = json_decode($re,true);
            //  dump($data);

            if($data['error'] == 0){
                $arr['code'] = 1000;
                $arr['m_code'] = $num;
                $arr['message'] = '请求成功';
            }else{
                $arr['code'] = 1002;
                $arr['m_code'] = $num;
                if($data['msg'] == 'FREQUENCE_ERROR'){
                    $arr['message'] = '请勿点击太快!';
                }
            }
            Cache::set('M_CODE',$num,3600);
            Cache::set('PHONE',$phone,3600);
            
        }
        return $arr;
    }
    // 企业版注册登录
    public function login(Request $request){
        if ($request) {
            $data = $request;
            //验证码成功
            $company_data = Db::table('social_user')
                ->where([
                    'phone' => $request['phone'],
                ])->first();
            $company_data =  json_decode(json_encode($company_data),true);
            // dump($company_data);die();
            if (count($company_data) == 0) {
                //不存在：注册+登陆
                //添加司机简称到企业
                $id =Db::table('social_company')->insertGetId([
                    'short_name'=>$request['short_name']
                ]);
                $reid =Db::table('social_limit_rule')->insertGetId([
                    'name'=>'限额为0',
                    'price'=>0,
                    'recovery_role'=>0,
                    'people'=>1,
                    'company_id'=>$id
                ]);
                $re =Db::table('social_user')->insertGetId([
                    'phone' =>$request['phone'],
                    'type'  =>3,
                    'role'  =>3,
                    'e_status'=>1,
                    'company_id'=>$id,
                    'limit_rule_id'=>$reid
                ]);
                if($re){
                    $last_data =Db::table('social_company')
                        ->join('social_user', 'social_company.id', '=', 'social_user.company_id')
                        ->where('social_user.phone',$request['phone'])
                        ->first();
                    $last_data =  json_decode(json_encode($last_data),true);
                    session('SOCIAL_USER_ID', $last_data['id']);
                    Db::table('company_server')->insertGetId([
                        'company_id'=> $last_data['id']
                    ]);
                    Db::table('company_fee')->insertGetId([
                        'company_id'=> $last_data['id']
                    ]);
                    return json_encode(['message' => '登录成功', 'code' => 1000]);
                }else{
                    return json_encode(['message' => '登录失败', 'code' => 1001]);
                }
            }elseif($company_data['type'] !=3){
                return json_encode(['message' => '你是企业普通员工,请使用会员登录', 'code' => 1002]);
            }else{
                $last_data =Db::table('social_company')
                    ->join('social_user', 'social_company.id', '=', 'social_user.company_id')
                    ->where('social_user.phone',$request['phone'])
                    ->first();
                $last_data =  json_decode(json_encode($last_data),true);
                session('SOCIAL_USER_ID', $last_data['id']);
                return json_encode(['message' => '登录成功', 'code' => 1000]);
            }
        }else{
            return json_encode(['message' => '登录失败,手机号不能为空', 'code' => 1004]);
        }
    }

    // 个人版注册登录
    public function login2(Request $request){

        //极光推送吗 放到session里
        // 验证码 手机号判断
        $arr = [];
        if($request['phone']){
            $data = $request->query();
            $jiguangcode = $data['jiguangcode']; //激光码
            // if($jiguangcode){
            //     session('jiguangcode',$jiguangcode);
            // }
            // dump(Cache::get('M_CODE'));
            $m_code = $data['m_code']; //验证码
            $session_code = Cache::get('M_CODE');
            $phone = Cache::get('PHONE');
            if($session_code == $m_code && $phone == $data['phone']){
                Cache::forget('M_CODE');
                Cache::forget('PHONE');
                $data['phone'] = $data['phone'];
                $re = Db :: table('social_user')->where('phone',$data['phone'])->first();
                $re =  json_decode(json_encode($re),true);
                if($re && $re['is_delete'] !=1){
                    $user['jpush_code'] = $jiguangcode;
                    $user['model_status'] = $data['model_status'];
                    $save = Db::table('social_user')->where('phone',$data['phone'])->update($user);
                    session('SOCIAL_USER_ID', $re['id']);
                    $users = User::where('phone',$data['phone'])->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                }elseif($re && $re['is_delete'] ==1){
                    $user['company_id'] = '';
                    $user['limit_rule_id'] = '';
                    $user['is_delete'] = 0;
                    $user['jpush_code'] = $jiguangcode;
                    $user['model_status'] = $data['model_status'];
                    $save = Db::table('social_user')->where('phone',$data['phone'])->update($user);
                    $users = User::where('phone',$data['phone'])->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                    session('SOCIAL_USER_ID', $re['id']);
                }else{
                    $insetArr = [
                        'phone'=>$data['phone'],
                        'jpush_code'=>$jiguangcode,
                        'model_status'=>$data['model_status']
                    ];
                    $id = Db :: table('social_user')->insertGetId($insetArr);
                    $users = User::where('id',$id)->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                    session('SOCIAL_USER_ID', $id);
                }
                $arr['code'] = 1000;
                $arr['message'] = '登录成功';
            }else{
                $arr['code'] = 1002;
                $arr['message'] = '登录失败,验证码不正确';
            }    
            // dump($users);
        }else{
            $arr['code'] = 1001;
            $arr['message'] = '登录失败,手机号不能为空';
        }
        return $arr;
    }

    // 注册协议
    public function xieyi(Request $request){
        if($request){
            return redirect('login/xieyi');
            // return redirect('http://www.baidu.com');
        }
    }
}
